package com.tongcao.cn.inteceptor;

import com.alibaba.common.convert.Convert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author:tongcao
 * @Date:2018/8/23 18:43
 * Description:基于URL实现的拦截器
 */
@Component
public class MyInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(MyInterceptor.class);

    public static final String starttime = "startTime";

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String path = httpServletRequest.getRequestURI().substring(httpServletRequest.getContextPath().length()).replaceAll("[/]+$", "");
        log.info("---------------------开始进入请求地址拦截-->" + path + "----------------------------");
        httpServletRequest.setAttribute(starttime, System.currentTimeMillis());
        /**
         * Session 校验
         */
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        log.info("--------------处理请求完成后视图渲染之前的处理操作---------------");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        Long cost = System.currentTimeMillis() - (Long) httpServletRequest.getAttribute(starttime);
        log.info("---------------视图渲染之后的操作-->" + cost + "ms-----------------------");
    }
}
